from sanic.views import HTTPMethodView
from sanic.response import text,json
import urllib3
import json as jn
from processing.other_func import ProToken,Sercret_all,Serialization,Random_id,date_format
from processing.Sql_DataFrom import ProJosn
from processing.comm import sqlPaging,sqlOrder,set_status,timestamp_to_standard

class addUserAddress(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        sql = f"""
            insert into user_address(address,openid,user_use,details,phone,userName,merchant_id,utime,ctime) values (%s,%s,%s,%s,%s,%s,%s,now(),now())
        """

        db.insert(sql,(
            html_data['city'],
            html_data['openid'],
            0,
            html_data['addr'],
            int(html_data['mobile']),
            html_data['name'],
            user_id,
        ))

        data = {
            'code':200,
            'message':'添加成功!'
        }
        return json(data)
class addressList(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        user_id = request.app.ctx.user_id
        openid = request.args.get('openid', '')
        sql = f"""
            select id,address,user_use,details,userName,phone from user_address where merchant_id=%s and openid=%s
        """
        sql_data = sqlOrder(sql, 'user_use', 'DESC')
        sql_order = db.find_all(sql_data,(user_id,openid))

        data = ProJosn(sql_order,['id','address','isdefult','moreAddres','name','phone'],list)

        data = {
            'code': 200,
            'data':{
                'list':data
            },
            'message': '添加成功!'
        }
        return json(data)
class deleteUserAddress(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        html_data = request.json

        sql = "delete from user_address where id=%s and openid=%s and merchant_id=%s"

        db.delete(sql,(html_data['id'],html_data['openid'],user_id))

        data = {
            'code':200,
            'message':'删除成功!'
        }
        return json(data)
class editUserAddress(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json

        sql = f"""
            update user_address set address=%s,details=%s,utime=now(),userName=%s,phone=%s where id=%s and merchant_id=%s and openid=%s
        """
        
        db.update(sql,(
            html_data['city'],
            html_data['addr'],
            html_data['name'],
            html_data['mobile'],
            html_data['id'],
            user_id,
            html_data['openid'],
        ))

        data = {
            'code':200,
            'message':'编辑成功!'
        }
        return json(data)
class useUserAddress(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        user_id = request.app.ctx.user_id
        html_data = request.json

        sql = f"""
            update user_address set user_use=0 where merchant_id=%s and openid=%s
        """
        db.update(sql,(user_id,html_data['openid']))

        sql = f"""
            update user_address set user_use=1 where merchant_id=%s and openid=%s and id=%s
        """
        db.update(sql, (user_id,html_data['openid'],html_data['id']))

        data = {
            'code': 200,
            'message': '设置默认!'
        }
        return json(data)

# 功能列表
class mallFunctionList(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.args.get('user_id','') or request.app.ctx.user_id
        client_ip = request.ip
        pageNum = int(request.args.get('pageNum', 1))
        pageSize = int(request.args.get('pageSize', 10))

        try:


            sql = f"""
                select id,title,name,icon,auths,frameSrc,menuType,showLink,menuRank from authority_menus where user_id='{user_id}' and menuType=3 or menuType=4
            """
            tol = f""" SELECT COUNT(*) FROM authority_menus where user_id='{user_id}'
                and menuType=3 or menuType=4
            """
            sql = sqlOrder(sql, 'menuRank', 'ASC')
            sql = sqlPaging(pageNum, pageSize, sql)

            sql_data = db.find_all(sql)
            tol_data = db.find_one(tol)
            if sql_data:

                data = ProJosn(sql_data,sql)
            else:
                data = []
            return json({'code': 200, 'message': "请求成功!", 'data': {
                'list':data,
                'total':tol_data[0]
            }})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/mallFunctionList', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

#
class addUserShoppingCart(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        openid = request.app.ctx.openid
        html_data = request.json
        sql_find =  f"""
            select goods_id from goods_shopping_cart where goods_id='{html_data["goods_id"]}' and openid='{openid}'
        """

        if db.find_one(sql_find):
            data = {
                'code': 201,
                'message': '该商品已存在购物车!'
            }
            return json(data)

        sql = f"""
            insert into goods_shopping_cart(goods_id,merchant_id,openid,goods_quantity,goods_price,goods_name,goods_image,goods_sku,goods_subtitle,ctime) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,now())
        """

        db.insert(sql,(
            html_data['goods_id'],
            user_id,
            openid,
            html_data['goods_quantity'],
            float(html_data['goods_price']),
            html_data['goods_name'],
            html_data['goods_image'],
            html_data['goods_sku'],
            html_data['goods_subtitle'],

        ))

        data = {
            'code':200,
            'message':'添加成功!'
        }
        return json(data)

class dianzan(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        openid = request.app.ctx.openid
        html_data = request.json
        sql = f"""
           update ai_data_all set likes=%s where id=%s and merchant_id=%s
        """

        db.update(sql, (
            int(html_data['likes']),
            html_data['id'],
            user_id,
        ))

        data = {
            'code':200,
            'message':'请求成功!'
        }
        return json(data)

class getCouponsData(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        client_ip = request.ip
        openid = request.app.ctx.openid
        user_id = request.app.ctx.user_id

        try:
            # 判断是否有可领取优惠券
            sql_Cs =  f"""
                select id,max_number,numbers,user_number from coupons 
                where merchant_id='{user_id}' and status='1' and (getCondition='弹窗发放' or getCondition='新人发放') AND endTime > NOW()
            """
            sql_Cs_data = db.find_all(sql_Cs)
            sql_Cs_data = ProJosn(sql_Cs_data,sql_Cs)
            for i in sql_Cs_data:
                # 判断用户是否已领取过
                sql_get = f"""
                    select id from my_coupons where openid='{openid}' and merchant_id='{user_id}' and coupons_id={i['id']}
                """
                #    用户满足领取条件 判断是否还有领取数量
                sql_num = f"""
                    select id from my_coupons where merchant_id='{user_id}' and coupons_id={i['id']}
                """
                tol = len(db.find_all(sql_num))
                if len(db.find_all(sql_get)) < i['max_number'] and tol <= i['numbers']:
                    sql_insert = f'insert into my_coupons(merchant_id,openid,coupons_id,status,ctime,utime ) VALUES (%s,%s,%s,%s,now(),now())'
                    db.insert(sql_insert, (
                        user_id,
                        openid,
                        i['id'],
                        '0'
                    ))

                    sql_update = f"""
                          update coupons set user_number=%s where id=%s
                    """
                    db.update(sql_update,(tol+1,i['id']))
                    if i['max_number'] == i['numbers']:
                        sql_update = f"""
                              update coupons set status=%s where id=%s
                        """
                        db.update(sql_update,('2',i['id']))
                else:

                    return json({'code': 201, 'message': "已被领取完！"
                                 })


            return json({'code': 200, 'message': "请求成功！"
            })
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/getCoupons/list', error))
            return json({'code': 200, 'message': "请求成功！"})